package org.feng.fxfront.util;

import javafx.collections.ObservableList;
import javafx.scene.control.TableColumn;
import javafx.scene.control.cell.PropertyValueFactory;
import org.feng.fxfront.sys.TableColumnDefine;
import org.feng.api.sys.annotations.TableColumnDesc;

import java.lang.reflect.Field;
import java.util.*;

/**
 * 表字段工具
 *
 * @author feng
 */
public class TableColumnUtil {

    private static final Map<Class<?>, Set<TableColumnDefine>> TABLE_COLUMN_DEFINES_MAP = new HashMap<>();


    public static <T> void parseColumnsByClass(ObservableList<TableColumn<T, ?>> columns, Class<T> clazz) {

        // 解析注解TableColumnDesc
        if (!TABLE_COLUMN_DEFINES_MAP.containsKey(clazz)) {
            Field[] declaredFields = clazz.getDeclaredFields();
            Set<TableColumnDefine> tableColumnDefineSet = new TreeSet<>(Comparator.comparingInt(TableColumnDefine::getOrder)
                    .thenComparing(TableColumnDefine::getFieldName));

            for (Field declaredField : declaredFields) {
                TableColumnDesc tableColumnDesc = declaredField.getAnnotation(TableColumnDesc.class);
                if (Objects.isNull(tableColumnDesc)) {
                    continue;
                }

                tableColumnDefineSet.add(new TableColumnDefine(tableColumnDesc, declaredField.getName()));
                TABLE_COLUMN_DEFINES_MAP.put(clazz, tableColumnDefineSet);
            }
        }

        // 创建表列
        Set<TableColumnDefine> tableColumnDefines = TABLE_COLUMN_DEFINES_MAP.get(clazz);
        for (TableColumnDefine tableColumnDefine : tableColumnDefines) {
            // 设置表头
            TableColumn<T, String> colum = new TableColumn<>(tableColumnDefine.getColumnDesc());
            // 设置表格列的具体属性
            colum.setCellValueFactory(new PropertyValueFactory<>(tableColumnDefine.getFieldName()));
            columns.add(colum);
        }
    }
}
